﻿using Account.Api.Dtos;
using Account.Api.Entitys;
using Cyss.Core;
using Cyss.Core.Repository;
using Cyss.Core.Repository.EF;
using System.Linq;

namespace Account.Api.Services
{
    /// <summary>
    /// 会员服务
    /// </summary>
    public class UserService : BaseService<User>
    {
        #region 字段
        /// <summary>
        /// 会员仓储
        /// </summary>
        private readonly IRepository<User> _userRepository;

        private readonly IRepository<Department> _deptRepository;

        private readonly MenuService _menuService;

        private readonly RolePermissionService _rolePermissionService;

        private readonly PermissionService _permissionService;

        private IMessageContext _message { set; get; }
        #endregion

        #region 构造函数

        /// <summary>
        ///     构造函数
        /// </summary>
        /// <param name="userRepository">会员 仓储</param>
        /// <param name="eventPublisher">事件发布者</param>
        public UserService(IRepository<User> userRepository,
            IRepository<Department> deptRepository,
             MenuService menuService,
            DepartmentService departmentService,
            RolePermissionService rolePermissionService,
            PermissionService permissionService,
            IMessageContext message
            ) : base(userRepository)
        {
            _userRepository = userRepository;
            _deptRepository = deptRepository;
            _menuService = menuService;
            _rolePermissionService = rolePermissionService;
            _permissionService = permissionService;
            _message = message;
        }

        #endregion

        #region 会员方法


        /// <summary>
        /// 分页获取 会员
        /// </summary>
        /// <param name="searchModel">查询model</param>
        /// <param name="showHidden"></param>
        /// <returns></returns>
        public virtual IPagedList<User> GetPageListUsers(UserSearchModel searchModel)
        {
            var query = _userRepository.TableNoTracking;
            var entitys = new PagedList<User>(query, searchModel);
            return entitys;
        }

        /// <summary>
        /// 分页获取 会员
        /// </summary>
        /// <param name="searchModel">查询model</param>
        /// <param name="showHidden"></param>
        /// <returns></returns>
        public virtual IPagedList<UserModel> GetPageListUserModels(UserSearchModel searchModel)
        {
            var query = from a in _userRepository.TableNoTracking
                        join b in _deptRepository.TableNoTracking on a.DeptId equals b.Id into bj
                        from b in bj.DefaultIfEmpty()
                        select new UserModel
                        {
                            Id = a.Id,
                            Number = a.Number,
                            Name = a.Name,
                            Remarks = a.Remarks,
                            Birthday = a.Birthday,
                            CardID = a.CardID,
                            Sex = a.Sex,
                            Pwd = a.Pwd,
                            Grade = a.Grade,
                            No = a.No,
                            Nickname = a.Nickname,
                            Phone = a.Phone,
                            EmergencyContact = a.EmergencyContact,
                            EmergencyContact_Phone = a.EmergencyContact_Phone,
                            PortraitRoute = a.PortraitRoute,
                            PortraitRoutePictureId = a.PortraitRoutePictureId,
                            IsEnabled = a.IsEnabled,
                            IsDeleted = a.IsDeleted,
                            DeptId = a.DeptId,
                            FileId=a.FileId,
                            DeptName = b != null ? b.Name : string.Empty
                        };

            var entitys = new PagedList<UserModel>(query, searchModel);
            return entitys;
        }

        #endregion

        #region 扩展

        public virtual bool EdidUserPassword(EditPasswordModel model)
        {
            var user = GetUser(model.UserNo, model.OldPassword);
            if (user == null)
            {
                _message.InsertMessage("旧密码错误！");
                return false;
            }
            if (model.NewPassword != model.ConfirmNewPassword)
            {
                _message.InsertMessage("新密码和确认密码不一致!");
                return false;
            }
            user.Pwd = EncryptHelper.MD5Encrypt(model.NewPassword);
            _userRepository.Update(user);
            return true;
        }


        public virtual User GetUser(string UserNo, string UserPwd)
        {
            UserPwd = EncryptHelper.MD5Encrypt(UserPwd);
            return _userRepository.Table.FirstOrDefault(x => x.No == UserNo && x.Pwd == UserPwd);
        }

        public virtual void GenerateLoginReturnModel(LoginReturnModel model)
        {
            var rolePermissions = _rolePermissionService.GetRolePermissionsByUserId(model.Id);
            var MenuIds = rolePermissions.Where(s => s.MenuId > 0).Select(s => s.MenuId);
            model.Menus = _menuService.Gets(x => MenuIds.Contains(x.Id)).ToList().Select(x => x.ToModel<MenuModel>());
            var roleperids = rolePermissions.Where(s => s.PermissionId > 0).Select(s => s.PermissionId).ToList();
            model.Permissions = _permissionService.Gets(x => roleperids.Contains(x.Id)).Select(x => x.ToModel<PermissionModel>());
        }
        #endregion

    }
}

